package com.ze.familyday.familyphotoframesquare;


import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONException;
import org.json.JSONObject;
   
import com.mouse.customview.CustomDialog;
import com.mouse.customview.CustomDialog.Builder;
import com.mouse.customview.CustomToast;
import com.umeng.analytics.MobclickAgent;
import com.ze.commontool.NetHelper;
import com.ze.commontool.PublicInfo;
import com.ze.commontool.UpdateTools;
import com.ze.familyday.familyphotoframesquare.R;
import com.ze.familydayverpm.userinfo.Componet;
import com.ze.familydayverpm.userinfo.UserInfoManager;
import com.ze.model.DataModel;
import com.ze.model.ModelDataMgr;


import android.app.Activity;
import android.app.AlertDialog;  
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class MainActivity extends BaseActivity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	public final static String TAG = "MainActivity";
	public final static int MSG_FIRST_CHECK = 3;
	//
	ArrayList<DataModel> arrayList = null;
	String  mUidString;
	int currentPage = 0;
	View wifiView;
	ListView wifiListView;
	View loginView;
	public static MainActivity instance;
	WifiManager wifiManager;
	ConnectivityManager conMan;
	AlertDialog wifiProgressDialog ;
	RelativeLayout mainLayout;
	private BroadcastReceiver mBroadcastReceiver = null;
	IntentFilter wifiFilter = null;
	private Context mContext;
	/**
	 * 充电状态
	 */
	public static int currentPlugged = 0;
	public static int lastPlugged = 0;
	int type = -1;
	
	/**
	 * 当前电量
	 */
	int currentLevel = -1;
	WifiLock wifiLock;
	LinearLayout mRoot;
	Button btn1;
	public static int WIFI_STATE = 0;
	private static boolean hasInitialization = false;
	/**
	 * 注册按钮
	 */
	private Button mRegiBtn;
	/**
	 * 密码可见
	 */
	private ImageButton mEyeIb;
	
	private Dialog batteryDialog;
	private Button btToLogin;
	private Button btToRegister;
	private Button btWifi;
	private RelativeLayout rlLogin;
	private Animation transAnimation;
	/**
	 * 标志性成员变量
	 */
	public static boolean needToShowUI = false;
	private Dialog mLoadingDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate");
		setContentView(R.layout.activity_pic);
		mContext = this;
		checkVerCod();
		initView();
		instance = this;
		
		
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifiManager.setWifiEnabled(true);
		conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		
		initReceiver();
		wifiFilter = new IntentFilter();  
		wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		//wifiFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		wifiFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(mBroadcastReceiver, wifiFilter);
		stateRegister = true;
		
		//By mouse 锁定wifi不休眠
		WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifiLock = manager.createWifiLock("SwiFTP");
		wifiLock.setReferenceCounted(false);
		wifiLock.acquire();
		
		//By mouse 停止服务
		Intent stopIntent = new Intent(mContext, PullImageService.class);
		mContext.stopService(stopIntent);
		//控制弹出键盘时 view上升高度
		controlKeyboardLayout(mRoot, btn1);
		
		
	}
	public static boolean isFirstFull = false;
	
	private void initView() {
		mRoot = (LinearLayout) findViewById(R.id.root);
		btn1 = (Button) findViewById(R.id.btn1);
		wifiView  = findViewById(R.id.signin_btnWifi);
		loginView = findViewById(R.id.signin_loginview);
		wifiView.setOnClickListener(onClickListener);
		mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
		mainLayout.setOnClickListener(onClickListener);
		mainLayout.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				checkVersion(executorService, MSG_FIRST_CHECK, handler);
				return false;
			}
		});
		mRegiBtn = (Button) findViewById(R.id.signin_btnRegi);
		mRegiBtn.setOnClickListener(onClickListener);
		mEyeIb = (ImageButton) findViewById(R.id.signin_eyeIb);
		mEyeIb.setOnClickListener(onClickListener);
		dialog_login					= findViewById(R.id.signin_btnSignIn);
		dialog_etUser 					= (EditText)findViewById(R.id.signin_etUser);
		dialog_etPw					= (EditText)findViewById(R.id.signin_etPw);
		dialog_login.setOnClickListener(onClickListener);
		loginView.setVisibility(View.INVISIBLE);
		btToLogin = (Button) findViewById(R.id.btToLogin);
		btToLogin.setOnClickListener(onClickListener);
		btToRegister = (Button) findViewById(R.id.btToRegister);
		btToRegister.setOnClickListener(onClickListener);
		btWifi = (Button) findViewById(R.id.btWifi);
		btWifi.setOnClickListener(onClickListener);
		rlLogin = (RelativeLayout) findViewById(R.id.rlLogin);
		transAnimation = new TranslateAnimation(1, 0.0f, 1, 1.0f, 1, 0.0f, 1, 0.0f);
		transAnimation.setDuration(300);
		mLoadingDialog = new CustomDialog.Builder(this)
		.setCustomButton(new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mLoadingDialog.dismiss();
			}
		})
		.create(1);
		mLoadingDialog.setCanceledOnTouchOutside(false);
	}
	
	public void checkVerCod()
	{
//		Componet componet = UserInfoManager.getInstance(MainActivity.this).getItem("username");
		SharedPreferences sharedPreferences = 
			this.getSharedPreferences("version.config", Activity.MODE_WORLD_WRITEABLE);
		String save_versionString = sharedPreferences.getString("version", "1.0");
		String cur_versionString = UpdateTools.GetVersion(MainActivity.this);
		if( !save_versionString.equals(cur_versionString) )
		{
			Editor editor = sharedPreferences.edit();
			editor.putString("version", cur_versionString);
			editor.commit();
			// 每次有更新包后先删除sd卡的缓存
			ModelDataMgr.getInstance().clear(0);
			ModelDataMgr.getInstance().clear(1);
			ModelDataMgr.getInstance().clear(2);
			ModelDataMgr.getInstance().clear(3);
			ModelDataMgr.getInstance().clear(4);
			
		}
		
		
	}
	
	/**
	 * By mouse
	 * @author Administrator
	 *
	 */
	private Dialog startDialog;
	class InitializationTask extends AsyncTask<Object, Object, Object>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (hasInitialization){
				return;
			}
			if (startDialog == null) {
				startDialog = new CustomDialog.Builder(mContext).create(2);
				startDialog.setCanceledOnTouchOutside(false);
			}
			if (!startDialog.isShowing())
				startDialog.show();
		}

		@Override
		protected Object doInBackground(Object... params) {
			int countTime = 0;
			if (!hasInitialization){
				while (!NetHelper.isNetAble(mContext) && countTime < 20){
					myDelay(1000);
					countTime ++;
				}
				if (NetHelper.isNetAble(mContext)) {
					WIFI_STATE = 1;
				}
				System.out.println("第一次初始化所用的时间countTime:" + countTime);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			if (startDialog != null && startDialog.isShowing()) {
				try {
					startDialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (!hasInitialization ){
				hasInitialization = true;  
			}
			System.out.println("showUI---4");
			showUI();
			needToShowUI = true;
				
		}
	}
	
	private void showUI() {
		if (WIFI_STATE == 1){
			if ( UserInfoManager.getInstance(MainActivity.this).getItem("m_auth") != null ) {
				isSaveMauth = true;
				downloadPicTask();
			} else {
				isSaveMauth = false;
				showLoginDialog();
				
			}
		} else {
			loginView.setVisibility(View.INVISIBLE);
			showSetWifiDialog();
		}
	}
	
	boolean stateRegister = false;
	boolean flagHasStart = false;
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.v(TAG, "onDestroy");
		if (stateRegister){
			stateRegister = false;
			unregisterReceiver(mBroadcastReceiver);
		}
		
		if( wifiLock != null && wifiLock.isHeld() )
		{
			wifiLock.release();
		}
		
		isDestroy = true;
	}
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		System.out.println("onResume");
		needToShowUI = false;
		
		if (batteryDialog != null && batteryDialog.isShowing()) {
			return;
		}
		
		if (!hasInitialization) {
			new InitializationTask().execute("");
		} else {
			System.out.println("showUI---1");
			showUI();
			needToShowUI = true;
		}
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		needToShowUI = false;
		try {
			if (mLoadingDialog != null) {
				mLoadingDialog.dismiss();
			}
			if (batteryDialog != null) {
				batteryDialog.dismiss();
			}
			if (startDialog != null) {
				startDialog.dismiss();
			}
			if (mWifiDialog != null) {
				mWifiDialog.dismiss();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	int testNum = 0;
	/**
	 * 
	 */
	public void onEnterFrame()
	{
		Log.v("cube", "第" + testNum + "次调用");
		testNum ++;
		 ConnectivityManager connectivityManager=(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
		 NetworkInfo net=connectivityManager.getActiveNetworkInfo();
		if( uselocal  || (net != null && net.isConnected()) )
		{
			if ( UserInfoManager.getInstance(MainActivity.this).getItem("m_auth") != null ) {
				isSaveMauth = true;
				downloadPicTask();
			}else
			{
				isSaveMauth = false;
				showLoginDialog();
			}
		}else
		{
		}
	}
	public boolean uselocal = false;
	public boolean isSaveMauth = false;
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	private View dialog_login 						= null;
	private EditText dialog_etUser 					= null;
	private EditText dialog_etPw 					= null;
	
	Animation loginViewAnimation = null;
	boolean FLAG_loginViewAnimation = false;
	public void showLoginDialog()
	{
		if (mWifiDialog != null && mWifiDialog.isShowing()) {
			System.out.println("执行mWifiDialog.dismiss();");
			mWifiDialog.dismiss();
		}
		if (loginView.getVisibility() != View.VISIBLE) {
			System.out.println("显示登录页面！");
			loginView.setVisibility(View.VISIBLE);
			if (!FLAG_loginViewAnimation){
				FLAG_loginViewAnimation = true;
				if ( loginViewAnimation == null ) {
					loginViewAnimation = new AlphaAnimation(0.0f, 1.0f);
					loginViewAnimation.setDuration(2000);
				}
				loginView.startAnimation(loginViewAnimation);
			}
		}
	}
	private String username;
	private String password;
	public boolean isLegalInput()
	{
		username = dialog_etUser.getText().toString().trim();
		if ( username.length() == 0 ) {
			CustomToast.show(mContext, R.string.tips_login_nameinput);
			return true;
		}
		password = dialog_etPw.getText().toString().trim();
		if ( password.length() == 0 ) {
			CustomToast.show(mContext, R.string.tips_login_pwinput);
			return true;
		}
		
		return false;
	}
	private boolean flagResetWifi = false;
	public void loginTask()
	{
		if( ! NetHelper.isNetAble(MainActivity.this))
		{
			CustomToast.show(mContext, R.string.invalid_network);
			return;
		}
		if (  !isLegalInput() ) {
			InputMethodManager immInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			immInputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), 0);
			if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
				mLoadingDialog.show();
			}
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					if (isDestroy) {
						return;
					}
					if ( ! isLogin) {
						if (mLoadingDialog != null && mLoadingDialog.isShowing())
							mLoadingDialog.dismiss();
						Dialog netDialog = new Builder(mContext).setMessage(R.string.invalid_connection)
						.setNegativeButton(R.string.try_again_login, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
									mLoadingDialog.show();
								}
								flagResetWifi = true;
								NetHelper.resetWifi(mContext);
								executorService.submit(new Runnable() {
									
									@SuppressWarnings("static-access")
									@Override
									public void run() {
										int count = 0;
										NetworkInfo.State state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
										while (state != NetworkInfo.State.CONNECTED && count < 30) {
											count ++;
											try {
												Thread.sleep(1000);
											} catch (InterruptedException e) {
												e.printStackTrace();
											}
											state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
										}
										handler.sendEmptyMessage(2);
									}
								});
							}
						})
						.setPositiveButton(R.string.other_net, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								openWifiLogin();
							}
						}).create(0);
						netDialog.setCanceledOnTouchOutside(false);
						netDialog.show();
					}
				}
			}, PublicInfo.MAX_TIME_FOR_lOGIN);
			isLogin = false;
			executorService.submit(new Runnable() {
				
				@Override
				public void run() {
					String responString = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_login), username
							, password);
					Message msg = handler.obtainMessage(1);
					msg.obj = responString;
					handler.sendMessage(msg);
				}
			});
		}
	}
	
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	private boolean isLogin = false;
	private OnClickListener onClickListener = new OnClickListener() {
		
		
		@Override
		public void onClick(View v) {
			if( v == dialog_login )
			{
				//友盟自定义事件
				MobclickAgent.onEvent(mContext, "user_login");
//				loginAlertDialog.hide();
				loginTask();
				
			}else if( v == btWifi )
			{
				MobclickAgent.onEvent(mContext, "wifi_login");
				openWifiLogin();
				//loginDialog.show();
			}else if( v == mainLayout ){
				//Toast.makeText(MainActivity.this, "Test", Toast.LENGTH_SHORT).show();
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		        imm.hideSoftInputFromWindow(dialog_etPw.getWindowToken(),0);
		        
			}else if (v == mRegiBtn) {
				registerTask();
			}else if (v == mEyeIb) {
				mEyeIb.setSelected(!mEyeIb.isSelected());
				if (mEyeIb.isSelected()) {
					dialog_etPw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
					System.out.println("密码可见！");
				}else {
					dialog_etPw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				}
				dialog_etPw.setSelection(dialog_etPw.getText().toString().length());
				Rect rect = new Rect();
				mRoot.getWindowVisibleDisplayFrame(rect);
				int[] location = new int[2];
                btn1.getLocationInWindow(location);
                int srollHeight = (location[1] + btn1.getHeight()) - rect.bottom;
                mRoot.scrollTo(0, srollHeight);
			}else if (v == btToLogin) {
				//rlLogin.startAnimation(transAnimation);
				btToLogin.setVisibility(View.INVISIBLE);
				mRegiBtn.setVisibility(View.INVISIBLE);
				dialog_login.setVisibility(View.VISIBLE);
				btToRegister.setVisibility(View.VISIBLE);
			}else if (v == btToRegister) {
				//rlLogin.startAnimation(transAnimation);
				btToRegister.setVisibility(View.INVISIBLE);
				mRegiBtn.setVisibility(View.VISIBLE);
				dialog_login.setVisibility(View.INVISIBLE);
				btToLogin.setVisibility(View.VISIBLE);
			}
			//TODO:
		}
	};
	public boolean ishaveOpenWifi = false;
	public void openWifiLogin()
	{
		//unregisterReceiver(receiver);
		ishaveOpenWifi = true;
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, WifiLoginActivity.class);
		startActivity(intent);
	}
	Handler handler = new Handler()
	{
		//TODO:handler
		@SuppressWarnings("static-access")
		public void handleMessage(android.os.Message msg) {
			int what = msg.what;
			try {
				switch (what) {
				case 1:
					// 登录
					isLogin = true;
					if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
						mLoadingDialog.dismiss();
					}
					JSONObject object = new JSONObject((String)msg.obj);
					if ( 0 == object.optInt("error", -1)) {
						if ( 1 == object.getJSONObject("data").getInt("return") )
						{
							// save m_auth
							Componet m_authComponet = new Componet("m_auth");
							m_authComponet.setValue(object.getJSONObject("data").getString("m_auth"));
							// save name
							Componet nameComponet = new Componet("name");
							nameComponet.setValue(object.getJSONObject("data").getString("name"));
							// save avatar
							Componet avatarComponet = new Componet("avatar");
							avatarComponet.setValue(object.getJSONObject("data").getString("avatar"));
							// save username  手机号码
							Componet usernameComponet = new Componet("username");
							usernameComponet.setValue(object.getJSONObject("data").getString("username"));
							// save uid
							Componet uidComponet = new Componet("uid");
							uidComponet.setValue(object.getJSONObject("data").getString("uid"));
							// save vip
							Componet vipComponet = new Componet("vip");
							vipComponet.setValue(object.getJSONObject("data").getString("vipstatus"));
							
							Componet preLoginUsername = UserInfoManager.getInstance(MainActivity.this).getItem("username");
							if( preLoginUsername != null &&
									! usernameComponet.getValue() .
									equals( preLoginUsername.getValue()))
							{
								// 与上一次登录不同
								ModelDataMgr.getInstance().clear(0);
								ModelDataMgr.getInstance().clear(1);
								ModelDataMgr.getInstance().clear(2);
								ModelDataMgr.getInstance().clear(3);
								ModelDataMgr.getInstance().clear(4);
							}
							UserInfoManager.getInstance(MainActivity.this).add(m_authComponet);
							UserInfoManager.getInstance(MainActivity.this).add(nameComponet);
							UserInfoManager.getInstance(MainActivity.this).add(avatarComponet);
							UserInfoManager.getInstance(MainActivity.this).add(usernameComponet);
							UserInfoManager.getInstance(MainActivity.this).add(uidComponet);
							UserInfoManager.getInstance(MainActivity.this).add(vipComponet);
//							Componet tempComponet = UserInfoManager.getInstance(SignInActivitiy.this).getItem("m_auth");
//							if ( tempComponet  != null ) {
////								UserInfoManager.getInstance(SignInActivitiy.this).delete(tempComponet);
//								tempComponet.setValue(m_authComponet.getValue());
//								Log.v("test", "xiugai:"+m_authComponet.getValue());
//							}else
//							{
//								UserInfoManager.getInstance(SignInActivitiy.this).add(m_authComponet);
//								Log.v("test", "new mauth:"+m_authComponet.getValue());
//							}
							UserInfoManager.getInstance(MainActivity.this).saveAll();
							FamilyDayVerPMApplication.bindJpush(MainActivity.this, uidComponet.getValue());
							downloadPicTask();
						}else
						{
							new Builder(mContext).setMessage(R.string.error_net).setPositiveButton(R.string.ok, null).create(0).show();
						}
					}else {
						new Builder(mContext).setMessage(R.string.invalid_account_or_password).setPositiveButton(R.string.ok, null).create(0).show();
					}
					
					break;
					
				case 2:
					if (conMan.getNetworkInfo(conMan.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
						loginTask();
					}else {
						if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
							mLoadingDialog.dismiss();
						}
						CustomToast.show(mContext, R.string.reconnect_tips);
					}
					flagResetWifi = false;
					break;

				case MSG_FIRST_CHECK :
					try {
						String cur_version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
						if ( ! cur_version .equals(msg.obj)) {
							CustomToast.show(mContext, R.string.new_version);
							download();
						}else {
							CustomToast.show(mContext, R.string.no_new_version);
						}
					} catch (NameNotFoundException e) {
						e.printStackTrace();
					}
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		};
	};
	
	public void downloadPicTask()
	{
		Intent intent = new Intent();
		intent.setClass(this, PhotoFrameActivity.class);
		intent.putExtra("uselocal", uselocal);
		intent.putExtra("isSaveMauth", isSaveMauth);
		startActivity(intent);
		Log.v(TAG, "执行startActivity(intent)");
		System.out.println("finish---686");
		MainActivity.this.finish();
	}
	
	private boolean isDestroy = false;
	
	
	public void myDelay(int time){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
     * @param root 最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 100) {
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //键盘隐藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }
    
    private void registerTask()
	{
		final String usernameString = dialog_etUser.getText().toString();
		if ( usernameString.length() != 11) {
			CustomToast.show(mContext, R.string.tips_input_phone_error);
			return;
		}
		final String pwString = dialog_etPw.getText().toString();
		if ( pwString.length() <= 0) {
			CustomToast.show(mContext, R.string.tips_input_pw_less0);
			return;
		}
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(dialog_etPw.getWindowToken(),0);
		
        final String name = usernameString.substring(0, 4) + "****" + usernameString.substring(8);
        
		new AsyncTask<String, String, String>(){
			protected void onPreExecute() {
				mLoadingDialog.show();
			};
			@Override
			protected String doInBackground(String... params) {
				String respon = NetHelper.getResponByHttpClient(
						getResources().getString(R.string.http_register),
						usernameString, pwString, name);
				return respon;
			}
			protected void onPostExecute(String result) {
				if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
					mLoadingDialog.dismiss();
				}
				try {
					JSONObject object = new JSONObject(result);
					if ( object.getInt("error") == 0 ) {
						
						UserInfoManager.getInstance(MainActivity.this).deleteAll();
						
						object = object.getJSONObject("data");
						Log.d("mouse", object.getInt("return") + "");
//						String uid = object.getInt("uid") + "";
//						String userString = object.getString("username");
//						String nameString = object.getString("name");
//						String avatar = object.getString("avatar");
//						String vipstatus = object.getString("vipstatus");
						// save m_auth
						Componet m_authComponet = new Componet("m_auth");
						m_authComponet.setValue(object.getString("m_auth"));
						// save name
						Componet nameComponet = new Componet("name");
						nameComponet.setValue(object.getString("name"));
						// save avatar
						Componet avatarComponet = new Componet("avatar");
						avatarComponet.setValue(object.getString("avatar"));
						// save username
						Componet usernameComponet = new Componet("username");
						usernameComponet.setValue(object.getString("username"));
						// save uid
						Componet uidComponet = new Componet("uid");
						uidComponet.setValue(object.getInt("uid") + "");
						// save vip
						Componet vipComponet = new Componet("vip");
						vipComponet.setValue(object.getString("vipstatus"));
						
						Componet preLoginUsername = UserInfoManager.getInstance(MainActivity.this).getItem("username");
						if( preLoginUsername != null &&
								! usernameComponet.getValue() .
								equals( preLoginUsername.getValue()))
						{
							// 与上一次登录不同
							ModelDataMgr.getInstance().clear(0);
							ModelDataMgr.getInstance().clear(1);
							ModelDataMgr.getInstance().clear(2);
							ModelDataMgr.getInstance().clear(3);
							ModelDataMgr.getInstance().clear(4);
						}
						UserInfoManager.getInstance(MainActivity.this).add(m_authComponet);
						UserInfoManager.getInstance(MainActivity.this).add(nameComponet);
						UserInfoManager.getInstance(MainActivity.this).add(avatarComponet);
						UserInfoManager.getInstance(MainActivity.this).add(usernameComponet);
						UserInfoManager.getInstance(MainActivity.this).add(uidComponet);
						UserInfoManager.getInstance(MainActivity.this).add(vipComponet);
						UserInfoManager.getInstance(MainActivity.this).saveAll();
						FamilyDayVerPMApplication.bindJpush(MainActivity.this, uidComponet.getValue());
						/*if (batteryDialog.isShowing()) {
							batteryDialog.dismiss();
						}
						BD_notice.setText("注册成功！恭喜您！");
						BD_btn.setTag("regi");
						batteryDialog.show();*/
						Dialog dialog = new CustomDialog.Builder(mContext).setMessage(String.format(getResources()
								.getString( R.string.tips_register_success ), pwString))
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent();
								intent.setClass(MainActivity.this, PhotoFrameActivity.class);
								intent.putExtra("uselocal", false);
								intent.putExtra("isSaveMauth", true);
								startActivity(intent);
								System.out.println("finish---830");
								MainActivity.this.finish();
							}
						})
						.create(0);
						dialog.setCanceledOnTouchOutside(false);
						dialog.show();
						
					}else {
						if (!object.isNull("msg")) {
							CustomToast.show(mContext, object.getString("msg") + "!");
						}else {
							CustomToast.show(mContext, R.string.register_failed);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			};
			
		}.execute("");
	}
    
    private Dialog mWifiDialog;
    private void showSetWifiDialog(){
    	if (mWifiDialog == null) {
    		mWifiDialog = new Builder(mContext).setMessage(R.string.set_wifi_notice)
				.setNegativeButton(R.string.play_no_net, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Componet userComponet = UserInfoManager.getInstance(MainActivity.this).getItem("username");
						if (userComponet == null){
							CustomToast.show(mContext, R.string.no_account_info);
							new InitializationTask().execute("");
							return;
						}
						uselocal = true;
						Intent localIntent = new Intent(MainActivity.this, PhotoFrameActivity.class);
						localIntent.putExtra("uselocal", true);
						startActivity(localIntent);
						System.out.println("finish---871");
						MainActivity.this.finish();
					}
				})
				.setPositiveButton(R.string.set_wifi, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						openWifiLogin();
						uselocal =false;
					}
				})
				.create(0);
    	    mWifiDialog.setCanceledOnTouchOutside(false);
		}
    	if (!mWifiDialog.isShowing()) {
    		System.out.println("mWifiDialog.show()---894");
    		mWifiDialog.show();
		}
    }
    
    private void initReceiver() {
    	mBroadcastReceiver = new BroadcastReceiver() {
			
			private Builder builder;
			
			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
					//获得网络连接服务   
				    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);   
				    // State state = connManager.getActiveNetworkInfo().getState();   
				    // 获取WIFI网络连接状态  
				    State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();   
				    // 判断是否正在使用WIFI网络   
				    if (State.CONNECTED == state) {
				    	System.out.println("WIFI网络");
				    	WIFI_STATE  = 1;
				    	handler.post(new Runnable() {
							
							@Override
							public void run() {
								wifiView.setBackgroundResource(R.drawable.main_wifi_on);
								if (needToShowUI && hasInitialization && !flagResetWifi) {
									System.out.println("showUI---2");
									showUI();
								}
							}
						});
				    	
				    } else {
				    	System.out.println("没有WIFI网络");
				    	WIFI_STATE = 0;
				    	handler.post(new Runnable() {
							
							@Override
							public void run() {
								wifiView.setBackgroundResource(R.drawable.main_wifi);
								if (needToShowUI && hasInitialization && !flagResetWifi) {
									System.out.println("shouUI---3");
									showUI();
								}
							}
						});
				    }
				} else if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
					type = intent.getIntExtra("plugged", -1);
					lastPlugged = currentPlugged;
					currentPlugged = type;
					if (lastPlugged != currentPlugged)
						isFirstFull = false;
					Log.v(TAG, "上次充电类型：" + lastPlugged);
					Log.v(TAG, "这次充电类型：" + currentPlugged);
					Log.v(TAG, "充电类型：" + type);
					int level = intent.getIntExtra("level", -1);
					int scale = intent.getIntExtra("scale", -1);
					if (level >= 0 && scale > 0)
						currentLevel = (level * 100) / scale;
					if (builder == null) {
						builder = new CustomDialog.Builder(mContext);
						builder.setPositiveButton("确定", null);
					}
					if (batteryDialog == null) {
						batteryDialog = builder.create(0);
					}
					if (batteryDialog != null && batteryDialog.isShowing())
						batteryDialog.dismiss();
					if (type == 1 && currentLevel >= 100 && !isFirstFull){
						isFirstFull = true;
						//batteryDialog.setMessage("充电已完成！");
						builder.setTvMessage("充电已完成！");
						batteryDialog.show();
					} else if (type == 1 && lastPlugged != currentPlugged) {
						builder.setTvMessage("正在充电！当前电量：" + currentLevel + "%");
						batteryDialog.show();
					}
					
				}
				
			}
		};
	}
    
   /* public void click1(View view){
    	Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
    	startActivity(intent);
    }*/

}
